package sg.edu.nus.iss.vmcs.store;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * @author Zaw
 * CashStoreItemIterator
 */

public class CashStoreItemIterator implements StoreItemIterator {
	private ArrayList<CashStoreItem> items = null;
	private int idx = 0;

	public CashStoreItemIterator(ArrayList<CashStoreItem> lsItems) {
		items = lsItems;
	}

	public StoreItem first() {
		return items.get(0);
	}

	public StoreItem next() {
		if (idx < items.size()) {
			idx++;
		}
		return items.get(idx - 1);
	}

	public boolean hasNext() {
		return (idx < items.size());
	}

	public StoreItem current() {
		return items.get(idx);
	}

	public void sortByWeight() {
		Collections.sort(this.items, new WeightComparator());
		idx = 0;
	}
	
	public void sortByQuantity(){
		Collections.sort(this.items, new QuantityComparator());
		idx = 0;
	}

	public void sortByAmount() {
		Collections.sort(this.items, new AmountComparator());
		idx = 0;
	}

	class WeightComparator implements Comparator<CashStoreItem> {
		public int compare(CashStoreItem o1, CashStoreItem o2) {
			Coin d1 = (Coin) o1.getContent();
			Coin d2 = (Coin) o2.getContent();
			int diff = (int) (d1.getWeight() - d2.getWeight());
			if (diff==0){
				diff = compareByValue(o1, o2);
			}
			return diff;
		}
	}

	class AmountComparator implements Comparator<CashStoreItem> {
		public int compare(CashStoreItem o1, CashStoreItem o2) {
			return compareByValue(o1, o2);
		}
	}
	
	class QuantityComparator implements Comparator<CashStoreItem> {
		public int compare(CashStoreItem o1, CashStoreItem o2) {
			int diff = o1.getQuantity() - o2.getQuantity();
			if (diff == 0) {
				diff = compareByValue(o1, o2);
			}
			return diff;
		}
	}
	
	private int compareByValue(CashStoreItem o1, CashStoreItem o2){
		Coin c1 = (Coin) o1.getContent();
		Coin c2 = (Coin) o2.getContent();
		
		return c1.getValue() - c2.getValue();
	}

}
